package com.engine.zhlx.financemoduel.pushdata.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author dusongsong
 * @date 2023年08月22日 11:45
 */
public class PushDataUtil {
    private static BaseBean baseBean = new BaseBean();


    /**
     * 校验参数
     *
     * @param paramsJson
     * @return
     */
    public String checkPushVendorParams(JSONObject paramsJson) {
        JSONObject inputJson = JSONObject.parseObject(paramsJson.getString("INPUT"));
        String dataHeader = Util.null2String(inputJson.getString("DATAHEADER"));
        String dataItem = Util.null2String(inputJson.getString("DATAITEM"));
        String fiItem = Util.null2String(inputJson.getString("FIITEM"));
        String purItem = Util.null2String(inputJson.getString("PURITEM"));
        if (!"".equals(dataHeader) && "".equals(dataHeader.trim())) {
            return "表头参数为空，请检查参数:DATAHEADER";
        }
        if (!"".equals(dataItem) && !isJSONArray(dataItem)) {
            return "JSON格式化错误，请检查参数:DATAITEM";
        }

        if (!"".equals(fiItem) && !isJSONArray(fiItem)) {
            return "JSON格式化错误，请检查参数:FIITEM";
        }
        if (!"".equals(purItem) && !isJSONArray(purItem)) {
            return "JSON格式化错误，请检查参数:PURITEM";
        }
        return "SUCCESS";
    }

    public boolean isJSONArray(String str) {
        boolean flag = false;
        if (!(str.trim().equals(""))) {
            try {
                JSONArray.parseArray(str);
                flag = true;
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 建模权限重构
     *
     * @param userid
     * @param formmodeid
     * @param id
     */
    public void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    public Map<String, Object> getMainField(JSONObject returnJson, String formid) {
        RecordSet rs = new RecordSet();
        Map<String, Object> map = new HashMap<>();
        rs.executeQuery("select fieldname from workflow_billfield where billid=? and viewtype=0", formid);
        while (rs.next()) {
            String fieldname = Util.null2String(rs.getString("fieldname")).toUpperCase();
            if (returnJson.containsKey(fieldname)) {
                map.put(fieldname, returnJson.getString(fieldname));
            }
        }
        return map;
    }

    public Map<String, Object> getDetailField(JSONObject returnJson, String formid, String deltablename) {
        RecordSet rs = new RecordSet();
        Map<String, Object> map = new HashMap<>();
        rs.executeQuery("select fieldname from workflow_billfield where billid=? and viewtype=1 and detailtable=?", formid, deltablename);
        while (rs.next()) {
            String fieldname = Util.null2String(rs.getString("fieldname")).toUpperCase();
            if (returnJson.containsKey(fieldname)) {
                map.put(fieldname, returnJson.getString(fieldname));
            }
        }
        return map;
    }

    /**
     * 将数据插入表单建模
     *
     * @param modeid
     * @param map
     * @return
     */
    public int insertModelData(int modeid, Map<String, Object> map) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        try {
            //查询该模块表名
            String sql = "select b.tablename,a.formid from modeinfo a left join workflow_bill b on a.formid=b.id where a.id=?";
            rs.executeQuery(sql, modeid);
            rs.next();
            String tablename = Util.null2String(rs.getString("tablename"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
            Object[] params = {uuid, 1, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
            if (rs.executeUpdate(insSql, params)) {
                rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
                rs1.next();
                dataid = Util.getIntValue(rs1.getString("id"));
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        updatesql += key + "='" + map.get(key).toString() + "',";
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        boolean updateStat = rs.executeUpdate(updatesql);
                        baseBean.writeLog(">>>>>insertModelData>>>>updatesql=" + updatesql);
                        if (!updateStat) {
                            dataid = 0;
                        }
                    }
                    //进行权限重构
                    newModeRight(1, modeid, dataid);
                }
            }
        } catch (Exception e) {
            baseBean.writeLog(">>>>>insertModelData>>>>" + e.getMessage());
        }

        return dataid;
    }

    /**
     * 更新明细数据
     *
     * @param tablename
     * @param map
     * @return
     */
    public boolean insertDetailData(String tablename, Map<String, Object> map) {
        String insertsql = "insert into " + tablename + "";
        String keyString = "";
        String valueString = "";
        boolean flag = false;
        RecordSet rs = new RecordSet();
        Set<String> keySet = map.keySet();
        try {
            for (String key : keySet) {
                if (map.get(key) == null || "".equals(map.get(key).toString())) {
                    continue;
                }
                keyString += key + ",";
                valueString += "'" + map.get(key).toString() + "',";
            }
            if (keyString.endsWith(",")) {
                keyString = keyString.substring(0, keyString.length() - 1);
            }
            if (valueString.endsWith(",")) {
                valueString = valueString.substring(0, valueString.length() - 1);
            }
            insertsql += "(" + keyString + ") values(" + valueString + ")";
            baseBean.writeLog(">>>>>insertDetailData>>>>insertsql=" + insertsql);
            flag = rs.executeUpdate(insertsql);
        } catch (Exception e) {
            baseBean.writeLog(">>>>>insertDetailData>>>>" + e.getMessage());
        }
        return flag;
    }

    /**
     * 更新数据
     *
     * @param tablename 表名
     * @param map       数据集合
     * @param dataid    更新用唯一标识
     * @return
     */
    public boolean updateModelData(String tablename, int dataid, Map<String, Object> map) {
        RecordSet rs = new RecordSet();
        String updatesql = "update " + tablename + " set  ";
        String valuesStr = "";
        boolean flag = false;
        try {
            Set<String> keySet = map.keySet();
            for (String key : keySet) {
                String value = Util.null2String(map.get(key).toString());
                if (valuesStr.equals("")) {
                    valuesStr = key + "='" + value + "'";
                } else {
                    valuesStr += "," + key + "='" + value + "'";
                }
            }
            updatesql += valuesStr + " where id='" + dataid + "'";
            baseBean.writeLog(">>>>>updateModelData>>>>updatesql=" + updatesql);
           flag = rs.execute(updatesql);
        }catch (Exception e){
            baseBean.writeLog(">>>>>updateModelData>>>>" + e.getMessage());
        }

        return flag;
    }

    /**
     * 删除数据
     *
     * @param tablename 表名
     * @param dataid    更新用唯一标识
     * @return
     */
    public boolean deleteDetailData(String tablename, int dataid) {
        RecordSet rs = new RecordSet();
        String deletesql = "delete " + tablename + " where mainid='" + dataid + "'";
        baseBean.writeLog(">>>>>deleteDetailData>>>>deletesql=" + deletesql);
        return rs.executeUpdate(deletesql);
    }


    /**
     * 获取建模Id
     *
     * @param tablename
     * @return
     */
    public int getFormmodeid(String tablename) {
        RecordSet rs = new RecordSet();
        String sql = "select m.id from modeinfo m left join workflow_bill b on m.formid = b.id where b.tablename = ?";
        rs.executeQuery(sql, tablename);
        rs.next();
        return Util.getIntValue(rs.getString("id"));
    }

    /**
     * 获取建模Id
     *
     * @param tablename
     * @return
     */
    public String getFormid(String tablename) {
        RecordSet rs = new RecordSet();
        String sql = "select id from  workflow_bill  where tablename=?";
        rs.executeQuery(sql, tablename);
        rs.next();
        return Util.null2String(rs.getString("id"));
    }

    /**
     * 获取是否存在重复数据
     *
     * @param tablename
     * @param fieldname
     * @param fieldvalue
     * @return
     */
    public int getMainId(String tablename, String fieldname, String fieldvalue) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from " + tablename + " where " + fieldname + "=?", fieldvalue);
        rs.next();
        return Util.getIntValue(rs.getString(1), -1);
    }

    /**
     * 获取银行信息
     *
     * @param yxdm
     * @return
     */
    public String getKhyh(String yxdm) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select yxmc from uf_sd_bk_jm where yxdm=?", yxdm);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

}
